package www.study.com;

//合并两个有序链表 https://leetcode.cn/problems/merge-two-sorted-lists/
public class code20 {
    public static void main(String[] args) {

    }

     public class ListNode {
         int val;
         ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    class Solution {
        public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
            ListNode head = null;
            ListNode now = null;
            ListNode node1 = list1;
            ListNode node2 = list2;
            while(node1 != null || node2 != null){
                ListNode chosedNode = null;
                if(node2 == null || node1 != null && node1.val <= node2.val){ //choose node1
                    chosedNode = node1;
                    node1 = node1.next; //1
                }else{
                    chosedNode = node2;
                    node2 = node2.next; //2
                }
                if(now == null){
                    now = new ListNode(chosedNode.val);
                    head = now;
                }else{
                    now.next = new ListNode(chosedNode.val);
                    now = now.next;
                }
                //chosedNode = chosedNode.next; 此行代码不能代替1和2，因为此行代码只是让chosedNode移动，node1和node2没有移动，注意
            }
            return head;
        }
    }
}
